package com.xbxkj.getway.config;

import com.alibaba.fastjson.JSONObject;
import com.xbxkj.util.Respons.ResponseUtil;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author 张子艺
 * @packge com.xbxkj.controller.config
 * @data 2019-07-17 18:24
 * @project MyCloud
 * 该过滤器 应注入在请求拦截的bean里
 */
@Configuration
public class RequestAuthFilter implements  Ordered, GatewayFilter {
    private static final String REQUEST_TIME_BEGIN = "requestTimeBegin";
    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {


        //权限认证
//            if(1<2){
//                List<String> token=exchange.getRequest().getHeaders().get("Authorization");
//                if(token==null){
//                    ServerHttpResponse serverHttpResponse = exchange.getResponse();
//                    HttpHeaders httpHeaders = serverHttpResponse.getHeaders();
//                    //设置headers
//                    httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
//                    httpHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
//                    serverHttpResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
//                    byte [] bytes= JSONObject.toJSONBytes(ResponseUtil.getTokenErrResponseMap() ) ;
//                    DataBuffer buffer = serverHttpResponse.bufferFactory().wrap(bytes);
//                    return exchange.getResponse().writeWith(Mono.just(buffer)) ;
//                }
//
//            }
        exchange.getAttributes().put(REQUEST_TIME_BEGIN, System.currentTimeMillis());
            //以上为pre 请求之前   then后是请求之后
        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    Long startTime = exchange.getAttribute(REQUEST_TIME_BEGIN);
                    if (startTime != null) {
                       System.err.println(exchange.getRequest().getURI().getRawPath() + ": " + (System.currentTimeMillis() - startTime) + "ms");
                    }
                })
        );
    }
}
